﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yuebon.Commons.Result;
using Yuebon.Security.IServices;

namespace Yuebon.Extensions.Middlewares
{
    public class LicenseMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILicenseService _licenseService;

        public LicenseMiddleware(RequestDelegate next, ILicenseService licenseService)
        {
            _next = next;
            _licenseService = licenseService;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            // 跳过授权检查的路由
            if (context.Request.Path.StartsWithSegments("/api/auth") ||
                context.Request.Path.StartsWithSegments("/health") ||
                context.Request.Path.StartsWithSegments("/api/token/VerifyLicense")) 
                
            {
                await _next(context);
                return;
            }

            //跳过服务器的检查
            if (context.Request.Host.Value == "localhost:8081" || HttpContextExtension.GetClientIpAddress(context)== "121.199.40.148")
            {
                await _next(context);
                return;
            }

            var licenseKey = Appsettings.GetValue("LicenseKey");
            var hardInfo = HardHelper.GetCpuInfo();

            if (string.IsNullOrEmpty(licenseKey))
            {                
                await context.Response.WriteAsync("License key is required");
                return;
            }


            if (string.IsNullOrEmpty(hardInfo))
            {               
                await context.Response.WriteAsync("hardInfo read error");
                return;
            }

            var strResult = HttpClientHelper.HttpGet($"http://www.czhz.online/api/token/VerifyLicense?licenseKey={licenseKey}&hardInfo={hardInfo}");
            var result = JsonConvert.DeserializeObject<CommonResult>(strResult);
            if (result == null) {
               
                await context.Response.WriteAsync("verify service error");
                return;
            }

            if (result.ErrCode == "1")
            {                
                await context.Response.WriteAsync(result.ErrMsg);
                return;
            }

            await _next(context);
        }


        
    }
}
